<template>
  <div class="setting-container">
    <div style="padding: 32px 15%">
      <div class="header-text">账号设置</div>
      <div class="main-content">
        <div class="main-content-item">
          <span>密码</span>
          <el-text
            style="cursor: pointer"
            type="primary"
            size="large"
            @click="pwdDialogVisible = true"
          >
            重置
          </el-text>
        </div>
        <div class="main-content-item">
          <span>电话</span>
          <div>
            <el-text style="margin-right: 16px" type="primary" size="large">
              {{ userStore.userInfo.phone }}
            </el-text>
            <el-text
              style="cursor: pointer"
              type="primary"
              size="large"
              @click="phoneDialogVisible = true"
            >
              修改
            </el-text>
          </div>
        </div>
        <div class="main-content-item">
          <span>邮箱绑定</span>
          <div v-if="userStore.userInfo.email">
            <el-text style="margin-right: 16px" type="primary" size="large">
              {{ userStore.userInfo.email }}
            </el-text>
            <el-text
              style="cursor: pointer"
              type="primary"
              size="large"
              @click="emailDialogVisible = true"
            >
              修改邮箱
            </el-text>
          </div>
          <el-text
            style="cursor: pointer"
            type="primary"
            size="large"
            v-else
            @click="emailDialogVisible = true"
          >
            绑定
          </el-text>
        </div>
        <div class="main-content-item">
          <span>账号注销</span>
          <el-popconfirm title="是否注销当前账号？" @confirm="deleteUser">
            <template #reference>
              <el-text
                style="cursor: pointer"
                type="primary"
                size="large"
                @click=""
              >
                注销
              </el-text>
            </template>
          </el-popconfirm>
        </div>
        <el-dialog
          v-model="pwdDialogVisible"
          title="修改密码"
          width="500"
          align-center
        >
          <el-form
            ref="pwdForm"
            :model="pwdFormData"
            :rules="pwdRules"
            @keyup.enter="submitPwdForm"
            style="margin: 24px auto; width: 420px"
          >
            <el-form-item prop="password">
              <el-input
                v-model="pwdFormData.password"
                show-password
                size="large"
                type="password"
                placeholder="请输入旧密码"
                prefix-icon="Lock"
              />
            </el-form-item>
            <el-form-item prop="newPassword">
              <el-input
                v-model="pwdFormData.newPassword"
                show-password
                size="large"
                type="password"
                placeholder="请输入新密码"
                prefix-icon="Lock"
              />
            </el-form-item>
            <el-form-item prop="resetPassword">
              <el-input
                v-model="pwdFormData.resetPassword"
                show-password
                size="large"
                type="password"
                placeholder="请重新输入密码"
                prefix-icon="Lock"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                size="large"
                style="width: 100%"
                @click="submitPwdForm"
              >
                修改并保存
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-dialog
          v-model="phoneDialogVisible"
          title="修改电话"
          width="500"
          align-center
        >
          <el-form
            ref="phoneForm"
            :model="phoneFormData"
            :rules="phoneRules"
            @keyup.enter="submitPhoneForm"
            style="margin: 24px auto; width: 420px"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="phoneFormData.phone"
                show-password
                size="large"
                type="password"
                placeholder="请输入新电话"
                prefix-icon="Lock"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                size="large"
                style="width: 100%"
                @click="submitPhoneForm"
              >
                修改并保存
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-dialog
          v-model="emailDialogVisible"
          :title="userStore.userInfo.email ? '修改邮箱' : '绑定邮箱'"
          width="500"
          align-center
        >
          <el-steps
            style="max-width: 600px; margin-bottom: 24px"
            :space="200"
            :active="active"
            simple
            v-if="userStore.userInfo.email"
          >
            <el-step title="旧邮箱验证" :icon="Message" />
            <el-step title="绑定新邮箱" :icon="Edit" />
          </el-steps>
          <el-form
            ref="emailForm"
            :model="emailFormData"
            :rules="emailRules"
            @keyup.enter="submitEmailForm"
            style="margin: 0 auto; width: 420px"
          >
            <el-form-item prop="email">
              <el-input
                type="email"
                v-model="emailFormData.email"
                size="large"
                placeholder="请输入邮箱"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input
                v-model="emailFormData.captcha"
                size="large"
                placeholder="请输入验证码"
                prefix-icon="CircleCheck"
              >
                <template #append>
                  <el-button
                    :disabled="countdown > 0"
                    @click="getEmailCaptcha()"
                  >
                    {{
                      countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码'
                    }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                size="large"
                style="width: 100%"
                @click="submitEmailForm"
              >
                {{ active === 0 ? '下一步' : '修改并保存' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { Edit, Message } from '@element-plus/icons-vue'
import {
  getEmailCaptchaBindingEmailByEmail,
  getEmailCaptchaNewEmailByEmail,
  getEmailCaptchaOldEmailByEmail,
  postUserEmail,
  postUserOldEmail,
  putUserEmail,
  deleteUserOne,
  putUserPwdByOld,
  putUserPhone,
} from '@/servers/controller'

const userStore = useUserStore()
const emailDialogVisible = ref(false)
const pwdDialogVisible = ref(false)
const phoneDialogVisible = ref(false)
const countdown = ref(0)
const active = ref(0)
const loading = ref(false)

let pwdForm = ref()
let pwdFormData = reactive({
  password: '',
  newPassword: '',
  resetPassword: '',
})

let phoneForm = ref()
let phoneFormData = reactive({
  phone: '',
})

const phoneRules = reactive({
  phone: [{ require: true, message: '请输入新电话', trigger: 'blur' }],
})

const checkPassword = (rule: any, value: any, callback: any) => {
  if (value.length < 6 || value.length > 16) {
    return callback(new Error('请输入6位到16位的密码'))
  } else {
    callback()
  }
}

const checkResetPassword = (rule: any, value: any, callback: any) => {
  if (value !== pwdFormData.newPassword) {
    return callback(new Error('密码不一致'))
  } else {
    callback()
  }
}

const pwdRules = reactive({
  password: [{ validator: checkPassword, trigger: 'blur' }],
  newPassword: [{ validator: checkPassword, trigger: 'blur' }],
  resetPassword: [
    { validator: checkPassword, trigger: 'blur' },
    {
      validator: checkResetPassword,
      trigger: 'blur',
    },
  ],
})

let emailForm = ref()
let emailFormData = ref({
  email: '',
  captcha: '',
})
const oldEmail = ref('')

const emailRules: any = reactive({
  email: [
    {
      required: true,
      type: 'email',
      message: '输入正确的邮箱',
      trigger: 'blur',
    },
  ],
  captcha: [
    { required: true, message: '输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '必须为六位验证码', trigger: 'blur' },
  ],
})

const submitPwdForm = async () => {
  await pwdForm.value.validate()
  try {
    const { message } = await putUserPwdByOld(pwdFormData)
    ElMessage.success(message)
    pwdDialogVisible.value = false
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const submitPhoneForm = async () => {
  await phoneForm.value.validate()
  try {
    console.log(phoneFormData)
    const { message } = await putUserPhone(phoneFormData)
    ElMessage.success(message)
    userStore.userInfo.phone = phoneFormData.phone
    phoneDialogVisible.value = false
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const getEmailCaptcha = async () => {
  await emailForm.value.validateField('email')
  try {
    if (userStore.userInfo.email) {
      if (active.value == 0) {
        const { message } = await getEmailCaptchaOldEmailByEmail({
          email: emailFormData.value.email,
        })
        ElMessage.success(message)
      } else {
        const { message } = await getEmailCaptchaNewEmailByEmail({
          email: emailFormData.value.email,
        })
        ElMessage.success(message)
      }
    } else {
      const { message } = await getEmailCaptchaBindingEmailByEmail({
        email: emailFormData.value.email,
      })
      ElMessage.success(message)
    }
    startTimer()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

const submitEmailForm = async () => {
  await emailForm.value.validate()
  if (userStore.userInfo.email) {
    if (active.value == 0) {
      submitOldEmailForm()
    } else {
      submitNewEmailForm()
    }
  } else {
    submitBindingEmailForm()
  }
}

const submitOldEmailForm = async () => {
  try {
    const { message } = await postUserOldEmail(emailFormData.value)
    ElMessage.success(message)
    oldEmail.value = emailFormData.value.email
    emailFormData.value = {
      email: '',
      captcha: '',
    }
    active.value++
    countdown.value = 0
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const submitNewEmailForm = async () => {
  try {
    const { message } = await putUserEmail({
      ...emailFormData.value,
      oldEmail: oldEmail.value,
    })
    ElMessage.success(message)
    await userStore.getUserInfo()
    emailDialogVisible.value = false
    emailFormData.value = {
      email: '',
      captcha: '',
    }
    active.value = 0
    countdown.value = 0
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const submitBindingEmailForm = async () => {
  try {
    const { message } = await postUserEmail(emailFormData.value)
    ElMessage.success(message)
    await userStore.getUserInfo()
    emailDialogVisible.value = false
    emailFormData.value = {
      email: '',
      captcha: '',
    }
    countdown.value = 0
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const startTimer = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const deleteUser = async () => {
  try {
    const { message } = await deleteUserOne()
    ElMessage.success(message)
    userStore.userLogout()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}
</script>

<style scoped lang="scss">
.setting-container {
  max-width: 100vw;
  min-width: 1200px;
  background: #dcdcdc8d;
  height: 100%;

  .header-text {
    font-size: 18px;
    font-weight: bold;
    border-bottom: solid 1px var(--el-menu-border-color);
  }

  .main-content {
    padding: 8px 128px;

    .main-content-item {
      display: flex;
      height: 68px;
      align-items: center;
      font-size: 17px;
      justify-content: space-between;
      border-bottom: solid 1px var(--el-menu-border-color);
    }
  }
}
</style>
